<template>
    <div>
      <div id="player"></div>
      <ElButton @click="handleTest">取流</ElButton>
    </div>
</template>
  
<script lang="ts" setup>
import { watch, ref, onBeforeUnmount, onMounted } from 'vue'
import cloudRenderer from "uesuperapi";
import { ComponentInstance } from '@/types/visual-app';

const props = defineProps<ComponentInstance>()

const emit = defineEmits<{
  (e: 'connection-info', payload: { code: number, msg: string }): void
  (e: 'register-cloud-response', payload: any): void
}>()

const isStreamConnected = ref(false);
(window as any).cloudRender = undefined;

const currentCloudUrl = ref('')
const currentAuthorization = ref('')
const currentAppid = ref('')
const currentAuto = ref(false)


// 启动渲染流
const openVideoStreaming = () => {
  emit('connection-info', {
    code: 0,
    msg: '请求启动渲染场景.'
  });
  Promise.race([
    fetch(`${currentCloudUrl.value}`, {
      method: "POST",
      headers: new Headers({
        "Content-type": "application/json",
        "Authorization": currentAuthorization.value || ''
      }),
      body: JSON.stringify({ appid: currentAppid.value, resX: window.innerWidth, resY: window.innerHeight })
    }),
    new Promise(function (resolve: any, reject) {
      setTimeout(() => reject(new Error('request timeout')), 1000 * 60)
    })])
    .then((res: any) => {
      if (!res.ok) {
        emit('connection-info', {
          code: -5,
          msg: res.statusText
        });
        throw Error(res.statusText)
      }
      return res.json()
    }).then(res => {
      if (res.code != 200) {
        emit('connection-info', {
          code: res.code,
          msg: res.msg
        });
        throw Error(res.msg)
      }
      return res.data
    }).then((data: any) => {
      (window as any).cloudRender = new cloudRenderer("player", 0);

      emit('connection-info', {
        code: 1,
        msg: '数字世界正在开启中...'
      });

      SuperAPI("OnStreamConnected", () => {
        isStreamConnected.value = true;
        emit('connection-info', {
          code: 2,
          msg: '数字世界已开启.'
        });
      });

      SuperAPI("OnStreamClosed", () => {
        isStreamConnected.value = false;
        emit('connection-info', {
          code: -1,
          msg: '数字世界已关闭.'
        });
      });

      SuperAPI("RegisterCloudResponse", function (e: any) {
        emit('register-cloud-response', e)
      });

      //开始开启视频
      SuperAPI("StartRenderCloud", getProxySocketUrl(data.url));

    }).finally(() => {
    });
}

const SuperAPI = (method: string, jsonData: any) => {
  if ((window as any).cloudRender) {
    (window as any).cloudRender.SuperAPI(method, jsonData);
  }
}

const closeVideoStreaming = () => {
  try {
    SuperAPI("StopRenderCloud", {});
  } catch (e) {
  }
  isStreamConnected.value = false;
  (window as any).cloudRender = undefined;
}

const startPickLocation = () => {
  var jsondata = {
    icon: false,
    info: false,
  }
  SuperAPI("StartPickLocation", jsondata);
}

const endPickLocation = () => {
    SuperAPI("EndPickLocation", {});
}

const getProxySocketUrl=(url:any)=> {
	const browserUrl = new URL(window.location.href);
	if('https:'===browserUrl.protocol){
		return  "wss://"+browserUrl.hostname+"/"+url.replace("ws://","");
	}else{
		return url;
	}
}

const handleTest=()=>{
  openVideoStreaming();
}


defineExpose({
  openVideoStreaming,
  closeVideoStreaming,
  SuperAPI,
  startPickLocation,
  endPickLocation,
  isStreamConnected
});

// 监听props变更，实时同步参数
watch(
  () => props.config?.attributes?.props,
  (val) => {
   
    if(val && val?.props){
      currentAppid.value = val.props.appid
      currentAuthorization.value = val.props.authorization
      currentCloudUrl.value = val.props.cloudUrl
      currentAuto.value=val.props.auto
      console.log('props=',val.props)
    }
  },
  { immediate: true, deep: true }
)


onBeforeUnmount(() => {
  try {
    SuperAPI("StopRenderCloud", {});
  } catch (e) {
  }
  isStreamConnected.value = false;
  (window as any).cloudRender = undefined;
})

onMounted(() => {
  if(currentAuto.value==true){
    //openVideoStreaming()
  }
})

</script>
  
<style scoped>
    #player {
        width: 100%;
        height: 100%;
    }
    #stats {
        position: absolute;
        z-index: 1000;
    }
</style>
  